import axios from 'axios'
import { showToast } from 'vant'
import router from '../router'

// 创建axios实例
const instance = axios.create({
  baseURL: '/api',
  timeout: 10000
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    const { response } = error
    
    if (response && response.status) {
      switch (response.status) {
        case 401:
          // 未授权，清除token并跳转到登录页
          localStorage.removeItem('token')
          router.replace({
            path: '/login',
            query: { redirect: router.currentRoute.value.fullPath }
          })
          break
        case 403:
          showToast('没有权限访问该资源')
          break
        case 404:
          showToast('请求的资源不存在')
          break
        case 500:
          showToast('服务器错误')
          break
        default:
          showToast(`连接错误 ${response.status}`)
      }
    } else {
      // 服务器未返回结果
      if (!window.navigator.onLine) {
        showToast('网络连接失败')
      } else {
        showToast('请求超时，请重试')
        return Promise.reject(error)
      }
    }
    
    return Promise.reject(error)
  }
)

export default instance
